package controller;

import jakarta.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.Supplier;
import pojo.SysUser;
import service.StorageRecordService;
import service.SupplierService;
import utils.Constants;
import utils.FileUpload;
import utils.PageSupport;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(value = "/sys/supplier")
public class SupplierController {
    private static final Logger log=Logger.getLogger(SupplierController.class);
    @Resource(name = "supplierService")
    private SupplierService supplierService;

    @Resource(name = "storageRecordService")
    private StorageRecordService storageRecordService;

    @RequestMapping(value = "/view")
    public String view(){
        log.info("查询供货商详情");
        return null;
    }

    @GetMapping("/supplierList")
    public String supplierList(Model model, String code, String name, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<Supplier> supplierList=null;
        System.out.println("code="+code+"name="+name+"pageIndex="+pageIndex);
        try{
            int pageSiz= Constants.pageSize;
            int totalCount=supplierService.selectCount(code, name);

            PageSupport pages=new PageSupport();
            pages.setNumberPage(pageSiz);
            pages.setCurrentPage(pageIndex-1);
            pages.setTotalPage(totalCount);

            int totalPageCount=pages.getTotalPage();

            if(pageIndex>totalPageCount){
                pageIndex=totalCount;
                throw new RuntimeException("页面不正确");
            }
            supplierList=supplierService.selectPages(name, code,pages.getCurrentPage()*pageSiz,pages.getNumberPage());
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("querySupName",name);
            model.addAttribute("querySupCode",code);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            log.error("查询供货商列表失败",e);
            return "redirect:/supplier/list";
        }

        return "supplier/list";
    }

    @GetMapping("/toAdd")
    public String toAdd(@ModelAttribute("supplier") Supplier supplier){
        return "supplier/add";
    }


    @PostMapping("/add")
    public String add(HttpSession session, Supplier supplier, HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false)MultipartFile[] attachs){
        SysUser user= (SysUser) session.getAttribute(Constants.USER_SESSION);
        log.info("添加供货商信息,name:"+supplier.getSupName());
        String companyLicPicPath=null;
        String orgCodePicPath=null;
        String errorInfo=null;
        boolean flag=true;

        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if(i==0){
                    errorInfo="uploadFileError";
                }else if(i==1){
                    errorInfo="uploadWpError";
                }
                String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
                log.info("uploadFile path======>" + path);
                log.info("上传文件路径:" + path);
                String oIdFileName = attach.getOriginalFilename(); // 原文件名
                log.info("原文件名:" + oIdFileName);
                String suffix = FilenameUtils.getExtension(oIdFileName); // 原文件后缀
                log.info("原文件后缀:" + suffix);
                int filesize = 50000000;
                if (attach.getSize() > filesize) { // 上传大小不得超过500kB
                    request.setAttribute("uploadFileError", "*上传文件不得大于500kB");
                    flag=false;
                } else if (suffix.equalsIgnoreCase("jpg")
                        || suffix.equalsIgnoreCase("png")
                        || suffix.equalsIgnoreCase("jpeg")
                        || suffix.equalsIgnoreCase("pneg")) { // 上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }

                    // 保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (IllegalStateException | IOException e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError", "*上传失败");
                        flag=false;
                    }
                    if(i==0){
                        companyLicPicPath = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
                    }else if(i==1){
                        orgCodePicPath=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+fileName;
                    }
                    log.info("companyLicPicPath:" + companyLicPicPath);
                    log.info("orgCodePicPath:" + orgCodePicPath);
                } else {
                    request.setAttribute(errorInfo, "*上传文件格式不正确");
                    flag=false;
                }
            }
        }
        supplier.setCreatedUserId(user.getRoleId());
        supplier.setCreatedTime(new Date());
        supplier.setCompanyLicPicPath(companyLicPicPath);
        supplier.setOrgCodePicPath(orgCodePicPath);
        if(supplierService.add(supplier) && flag){
            return "redirect:/sys/supplier/supplierList";
        }
        return "supplier/add";
    }


    @GetMapping("/view/{id}")
    public String toView(Model model,@PathVariable Integer id){
        Supplier supplier=null;
        try{
            supplier=supplierService.selectById(id);
            model.addAttribute("supplier",supplier);
        }catch (Exception e){
            log.error("查询供货商详情失败",e);
            return "redirect:/supplier/list";
        }
        return "supplier/view";
    }

    @GetMapping("/toUpdate/{id}")
    public String toUpdate(Model model,@PathVariable Integer id,HttpSession session){
        Supplier supplier=null;
        try{
            supplier=supplierService.selectById(id);
            supplier.setCompanyLicPicPath(FileUpload.existsPath(supplier.getCompanyLicPicPath(),session));
            supplier.setOrgCodePicPath(FileUpload.existsPath(supplier.getOrgCodePicPath(),session));
            model.addAttribute("supplier",supplier);
        }catch (Exception e){
            log.error("查询供货商详情失败",e);
            return "redirect:/supplier/list";
        }
        return "supplier/update";
    }

    @PostMapping("/update")
    public String update(HttpSession session,HttpServletRequest request,Supplier supplier){
        SysUser user= (SysUser) session.getAttribute(Constants.USER_SESSION);
        String uploadPath=session.getServletContext().getRealPath(Constants.UPLOAD_PATH);

        supplier.setUpdatedUserId((long) user.getId());
        supplier.setUpdatedTime(new Date());
        if (supplier.getCompanyLicPicPath()!=null){
            // 提取文件上传的方法
            String path = FileUpload.multipartFileUpload(uploadPath, (MultipartFile) supplier.getCompanyLicPicPath());
            // Web访问的路径（不是文件上传的磁盘位置）
            if (path == null) {
                request.setAttribute("error1","企业营业执照文件有问题");
                return "sysUser/update";
            }
            log.debug("企业营业执照path:"+path);
            // 设置企业营业执照路径
            supplier.setCompanyLicPicPath(path);
        }

        if (supplier.getOrgCodePicPath()!=null){
            // 提取文件上传的方法
            String path = FileUpload.multipartFileUpload(uploadPath, (MultipartFile) supplier.getOrgCodePicPath());
            // Web访问的路径（不是文件上传的磁盘位置）
            if (path == null) {
                request.setAttribute("error2","组织机构代码证文件有问题");
                return "sysUser/update";
            }
            log.debug("组织机构代码证path:"+path);
            // 设置组织机构代码证路径
            supplier.setOrgCodePicPath(path);
        }
        if(supplierService.update(supplier)){
            return "redirect:/sys/supplier/supplierList";
        }
        return "supplier/update";
    }

    @DeleteMapping("/del/{supId}")
    @ResponseBody
    public Object del(@PathVariable("supId") int supId,HttpSession session){
        Map<String,String> map= new HashMap<>();
        Supplier supplier=supplierService.selectById(supId);

        int storageRecordCount=storageRecordService.selectCountBySupId(supId);
        if(storageRecordCount==0) {
            List<String> paths = new ArrayList<>();
            if (supplier.getOrgCodePicPath() != null) {
                paths.add((String) supplier.getOrgCodePicPath());
            }
            if (supplier.getCompanyLicPicPath() != null) {
                paths.add((String) supplier.getCompanyLicPicPath());
            }
            // 删除证件
            for (int i = 0; i < paths.size(); i++) {
                String path = session.getServletContext().getRealPath(paths.get(i));
                File file = new File(path);
                if (file.exists()) {
                    System.out.println("删除图片:" + path);
                    file.delete();
                }
            }
            // 删除所有相关的入库记录
//        storageRecordService.deleteBySupId(supId);

            // 删除供应商
            if (supplierService.delete(supId)) {
                map.put("delResult", "true");
            } else {
                map.put("delResult", "false");
            }
        }else if (storageRecordCount>0) {
            map.put("delResult", String.valueOf(storageRecordCount));
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("/simpleList")
    public List<Supplier> simpleList(){
        return supplierService.selectAllSuppliers();
    }
}
